<?php

// +----------------------------------------------------------------------
// | card版本接口index
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\v3;

use app\model\app\Modular as ModularModel;
use app\model\pos\Pos as PosModel;
use app\model\pos\PosUser as PosUserModel;
use app\model\pos\PosVip as PosVipModel;
use app\model\pos\UserPosLevel as UserPosLevelModel;
use app\model\store\Address as AddressesModel;
use app\event\pos\PosTransfer as PosTransferEvent;
use app\model\ucenter\User as UserModel;
use app\model\pos\PosTrade as PosTradeModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\pos\Store as StoreModel;
use app\model\pos\PosItem as PosItemModel;
use think\Exception;

class Pos extends Common
{

    /**
     * 首页
     */
    public function index()
    {
        if ($this->user) {
            $data['info']['trade'] = PosTradeModel::where('user_id', $this->user['id'])->whereTime('create_time', 'month')->sum('amount');
            $data['info']['profit'] = UserMoneyLogModel::where('user_id', $this->user['id'])->where('type', 90)->whereTime('create_time', 'month')->sum('money');;
            $data['info']['my_balance'] = $this->user['my_balance'];
            $data['info']['level'] = UserPosLevelModel::where('user_id', $this->user['id'])->order('id DESC')->value('level') ?: 0;
            $data['vips'] = PosVipModel::with(['cover', 'image'])->hidden(['body'])->where('status', 1)->where('is_show', 1)->select();
            $data['modular'] = ModularModel::with('image')->where('status', 1)->where('id', 16)->find();
            return $this->successAjax($data);
        } else {
            throw new Exception('请先登录');
        }

    }

    /**
     * 首页
     */
    public function item()
    {
        $data['items'] = PosItemModel::with('cover')->where('status', 1)->select();
        $data['address'] = AddressesModel::where('user_id', $this->user['id'])->where('status', 1)->order('is_default DESC')->find();
        $data['tips'] = '请选择您要的产品';
        return $this->successAjax($data);
    }

    /**
     * 我的购物车
     */
    public function sysnc()
    {
        $items = $this->request->param('items/a', []);
        $number = 0;
        $price = 0;

        foreach ($items as $item) {
            $number += $item['number'];
        }
        if ($number >= 50) {
            $tips = '当前数量' . $number . '，可以享受V3权益';
        } elseif ($number >= 5) {
            $tips = '当前数量' . $number . '，可以享受V2权益';
        } else {
            $tips = '当前数量' . $number . '，可以享受V1权益';
        }
//			dump($data['data']['store_buy']['goods']);
        $data['number'] = $number;;
        $data['price'] = $price * 69;;
        $data['tips'] = $tips;

        return $this->successAjax($data);
    }

    /**
     * pos终端首页
     * @return \think\response
     */
    public function device()
    {
        $data['info']['wait_bind'] = $this->user->poses()->whereNull('bind_time')->where('status', 1)->count();
        $data['info']['has_bind'] = $this->user->poses()->whereNotNull('bind_time')->where('status', 1)->count();
        $data['info']['has_transfer'] = PosUserModel::where('status', 1)->where('last_user_id', $this->user['id'])->count();
        $data['info']['all'] = $this->user->poses()->where('status', 1)->count();
        $data['tab'] = $this->request->param('tab');
        $tab = $this->request->param('tab', '');
        $search_sn = $this->request->param('search_sn', '');
        if ($tab == 2) {
            // 划拨
            $data['lists'] = PosUserModel::with(['user', 'pos'])->where('status', 1)->when($search_sn, function ($query) use ($search_sn) {
                $query->where('sn', 'like', '%' . $search_sn . '%');
            })->where('last_user_id', $this->user['id'])->order('create_time DESC')->paginate(50);
        } else {
            $data['lists'] = $this->user->poses()->with(['store', 'pos_level'])->when($search_sn, function ($query) use ($search_sn) {
                $query->where('sn', 'like', '%' . $search_sn . '%');
            })->when(1, function ($query) use ($tab) {
                if ($tab == 0) {
                    $query->whereNull('bind_time');
                } else {
                    $query->whereNotNull('bind_time');
                }
            })->where('status', 1)->append(['channel'])->order('update_time DESC')->paginate(50);
        }
        return $this->successAjax($data);
    }
//    /**
//     * pos终端首页
//     * @return \think\response
//     */
//    public function device()
//    {
//        $data['info']['wait_bind'] = $this->user->poses()->whereNull('bind_time')->where('status', 1)->count();
//        $data['info']['wait_activate'] = $this->user->poses()->whereNotNull('bind_time')->whereNotNull('transfer_time')->count();
//        $data['info']['activate'] = $this->user->poses()->whereNotNull('bind_time')->whereNull('transfer_time')->count();
//        $data['info']['all'] = $this->user->poses()->count();
//        $data['tab'] = $this->request->param('tab');
//        $tab = $this->request->param('tab', '');
//        $search_sn = $this->request->param('search_sn', '');
//        if ($tab == 3) {
//            // 划拨
//            $data['lists'] = PosUserModel::with(['user', 'pos'])->where('status', 1)->when($search_sn, function ($query) use ($search_sn) {
//                $query->where('sn', 'like', '%' . $search_sn . '%');
//            })->where('last_user_id', $this->user['id'])->order('create_time DESC')->paginate(50);
//        } else {
//            $data['lists'] = $this->user->poses()->when($search_sn, function ($query) use ($search_sn) {
//                $query->where('sn', 'like', '%' . $search_sn . '%');
//            })->when(1, function ($query) use ($tab) {
//                if ($tab == 0) {
//                    $query->whereNull('bind_time');
//                } elseif ($tab == 1) {
//                    $query->whereNotNull('bind_time')->whereNull('transfer_time');
//                } elseif ($tab == 2) {
//                    $query->whereNotNull('bind_time')->whereNotNull('transfer_time');
//                }
//            })->where('status', 1)->order('update_time DESC')->paginate(50);
//        }
//        return $this->successAjax($data);
//    }

    /**
     * 可以调拨设备
     */
    public function nobind()
    {
        $search_sn = $this->request->param('search_sn', '');
        $data['lists'] = $this->user->poses()->with('pos_level')
            ->append(['channel'])
            ->when($search_sn, function ($query) use ($search_sn) {
                $query->where('sn', 'like', '%' . $search_sn . '%');
            })->whereNull('bind_time')->where('status', 1)->order('sn ASC')->paginate(50);
        return $this->successAjax($data);
    }

    public function transfer()
    {
        if ($this->request->isPost()) {
            $event = new PosTransferEvent();
            $data = $event->transfer($this->request->param(), $this->user);
            return $this->autoAjax($data);
        } else {
            if (1 == $this->request->param('type', 0)) {
                // 按序列号
                $lists = $this->user->poses()->with('pos_level')->whereNull('bind_time')->where('status', 1)->order('sn ASC')->select();
                $pos = [];
                $start_sn = $this->request->param('start_sn', '');
                $quantity = $this->request->param('quantity', 0);
                $start = false;
                foreach ($lists as $list) {
                    if ($list['sn'] == $start_sn || $start) {
                        $start = true;
                        if (count($pos) < $quantity) {
                            $pos[] = $list;
                        }
                    }
                }
            } else {
                $pos = $this->user->poses()->with('pos_level')->where('id', 'in', $this->request->param('pos_ids'))->whereNull('bind_time')->where('status', 1)->select();
            }
            $data['lists'] = $pos;
            return $this->successAjax($data);
        }

    }
    public function back()
    {
        if ($this->request->isPost()) {
            $event = new PosTransferEvent();
            $data = $event->back($this->request->param(), $this->user);
            return $this->autoAjax($data);
        } else {

            if (1 == $this->request->param('type', 0)) {
                // 按序列号
                $lists = $this->user->poses()->with('pos_level')->whereNull('bind_time')->where('status', 1)->order('sn ASC')->select();
                $pos = [];
                $start_sn = $this->request->param('start_sn', '');
                $quantity = $this->request->param('quantity', 0);
                $start = false;
                foreach ($lists as $list) {
                    if ($list['sn'] == $start_sn || $start) {
                        $start = true;
                        if (count($pos) < $quantity) {
                            $pos[] = $list;
                        }
                    }
                }
            } else {
                $pos = $this->user->poses()->with('pos_level')->where('id', 'in', $this->request->param('pos_ids'))->whereNull('bind_time')->where('status', 1)->select();
            }
            $data['lists'] = $pos;
            return $this->successAjax($data);
        }

    }

    public function transfer_team()
    {

        $search_mobile = $this->request->param('search_mobile', '');
        // 我的直属
        $data['lists'] = UserModel::where('bid', $this->user['id'])->when($search_mobile, function ($query) use ($search_mobile) {
            $query->where('nickname|mobile', 'like', '%' . $search_mobile . '%');
        })->field('id,nickname,mobile')->paginate(50);

        return $this->successAjax($data);
    }

    public function detail()
    {
        $data['detail'] = PosVipModel::with(['cover', 'image'])->where('id', $this->request->param('id'))->where('status', 1)->find();
        $data['address'] = AddressesModel::where('user_id', $this->user['id'])->where('status', 1)->order('is_default DESC')->find();
        return $this->successAjax($data);
    }

    /**
     * 我的团队
     */
    public function team()
    {
        $team = $this->user->teams()->where('status', 1)->column('id');
        $data['data']['teams'] = $this->user->teams()->order('id DESC')->paginate();
        $data['data']['info']['month_open'] = PosModel::where('user_id', 'in', $team)->whereTime('activate_time', 'month')->count();
        $data['data']['info']['all_open'] = PosModel::where('user_id', 'in', $team)->whereNotNull('activate_time')->count();
        $data['data']['info']['level'] = UserPosLevelModel::where('user_id', $this->user['id'])->order('id DESC')->value('level');
        $data['code'] = 0;
        return $this->json($data);
    }

    public function trade()
    {
        $brand_id = $this->request->param('brand_id', 0);
        $brand_id--;
        $brands = [['id' => -1, 'name' => '全部']];
        foreach (PosModel::$channel as $index => $item) {
            $brands[] = ['id' => $index, 'name' => $item];
        }
        foreach ($brands as $index => $brand) {
            $brands[$index]['info']['today']['money'] = PosTradeModel::where('user_id', $this->user['id'])
                ->where('type', 1)->when($brand['id'] != -1, function ($query) use ($brand) {
                    $query->where('channel_id', $brand['id']);
                })->whereTime('trans_time', 'today')->sum('amount');
            $brands[$index]['info']['today']['number'] = PosTradeModel::where('user_id', $this->user['id'])->where('type', 1)->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel_id', $brand['id']);
            })->whereTime('trans_time', 'today')->count();
            $brands[$index]['info']['month']['money'] = PosTradeModel::where('user_id', $this->user['id'])->where('type', 1)->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel_id', $brand['id']);
            })->whereTime('trans_time', 'month')->sum('amount');
            $brands[$index]['info']['month']['number'] = PosTradeModel::where('user_id', $this->user['id'])->where('type', 1)->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel_id', $brand['id']);
            })->whereTime('trans_time', 'month')->count();

        }
        $data['lists'] = PosTradeModel::with('store')->where('user_id', $this->user['id'])->where('type', 1)->when($brand_id > -1, function ($query) use ($brand_id) {
            $query->where('channel_id', $brand_id);
        })->order('id DESC')->paginate();
        $data['tab'] = $brands;
        return $this->successAjax($data);
    }

    public function profit()
    {
        $brand_id = $this->request->param('brand_id', 0);
        $brand_id--;
        $brands = [['id' => -1, 'name' => '全部']];
        foreach (PosModel::$channel as $index => $item) {
            $brands[] = ['id' => $index, 'name' => $item];
        }
        foreach ($brands as $index => $brand) {
            /**
             *
             * '90'=> 'POS交易返佣',
             * '91'=> '流量返现（专项）',
             * '92'=> '交易返现（专项）',*/
            $brands[$index]['info']['today']['fee'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 90)->whereTime('create_time', 'today')->sum('money');
            $brands[$index]['info']['today']['gift'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 92)->whereTime('create_time', 'today')->sum('money');
            $brands[$index]['info']['today']['flow'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 91)->whereTime('create_time', 'today')->sum('money');
            $brands[$index]['info']['month']['gift'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 92)->whereTime('create_time', 'month')->sum('money');
            $brands[$index]['info']['month']['flow'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 91)->whereTime('create_time', 'month')->sum('money');
            $brands[$index]['info']['month']['fee'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand['id'] != -1, function ($query) use ($brand) {
                $query->where('channel', $brand['id']);
            })->where('type', 90)->whereTime('create_time', 'month')->sum('money');
//            $brands[$index]['info']['month']['fee'] = rand(100, 999);
        }

        $data['lists'] = UserMoneyLogModel::where('user_id', $this->user['id'])->when($brand_id != -1, function ($query) use ($brand_id) {
            $query->where('channel', $brand_id);
        })->where('type', 'in', '90,91,92')->order('id DESC')->paginate();
        $data['tab'] = $brands;
        return $this->successAjax($data);
    }

    public function store()
    {

        $data['info']['team'] = 0;
//        $data['info']['team'] = StoreModel::where('user_id', $this->user['id'])->whereTime('create_time', 'today')->count();
        $data['info']['my'] = StoreModel::where('user_id', $this->user['id'])->whereTime('create_time', 'today')->count();
        $data['info']['all'] = $data['info']['team'] + $data['info']['my'];
//        $data['lists'] = StoreModel::where('user_id', $this->user['id'])->order('id DESC')->paginate();
        $data['lists'] = StoreModel::where('user_id', $this->user['id'])->order('id DESC')->paginate();
//        $data['lists'] = StoreModel::where('status', 1)->order('id DESC')->paginate();

        return $this->successAjax($data);
    }

}
